from rest_framework.viewsets import ModelViewSet

from user.models import *
from user.serializer import *
from django_redis import get_redis_connection
from rest_framework.views import APIView
from rest_framework.response import Response
from user.tasks import send_mail_task
from user.permissions import WorkPermission
from rest_framework.permissions import IsAuthenticated, IsAdminUser, AllowAny


class RegisterView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        email = request.data.get('email')
        phone = request.data.get('phone')
        print(username, password, email, phone)

        if not all([username, password, email, phone]):
            return Response({'code': '401', 'msg': '信息不完整'})

            # 从redis中获取手机验证码进行校验
        redis_cli = get_redis_connection("img_code")
        redis_phone_num = redis_cli.get(phone).decode()
        if redis_phone_num != request.data.get("code"):
            return Response({"code": 4005, 'msg': "短信验证码错误"}, status=200)

        user_obj = User.objects.create(
            username=username,
            password=make_password(password),
            phone=phone,
        )
        return Response({'code': 200, 'msg': '注册成功'})

    # return Response({'code':400,'msg':'注册失败'})


# class LoginView(APIView):
#     def post(self, request):
#         username = request.data.get('username')
#         password = request.data.get('password')
#
#         user_obj = User.objects.filter(username=username, password=password).first()
#
#         if user_obj:
#             return Response({'code': 200, 'msg': '登陆成功'})
#
#         return Response({'code': 400, 'msg': '登陆失败'})


def jwt_response_payload_handler(token, user=None, request=None):
    """
        自定义登陆返回的信息
        :param token: jwt生成的token值
        :param user: User对象
        :param request: 请求
    """
    return {
        'token': token,
        "username": user.username,
        # "authenticated": True,
        # "role": None,
        'id': user.id,
        'msg': '登录成功',
        # "email": user.email
    }


class CheckUserInfo(APIView):
    """
    用户名或者手机号是否存在
    """

    def post(self, request):
        type = request.data.get("type")

        data = request.data.get("data")

        if not all([type, data]):
            return Response({"code": 4005, "msg": "参数不完整"})

        if type == "username":
            count = User.objects.filter(username=data).count()
        elif type == "phone":
            count = User.objects.filter(phone=data).count()
        else:
            return Response({"code": 4009, "msg": "参数不正确"})

        data = {
            "code": 0,
            'msg': "成功",
            "data": {
                "type": type,
                "count": count
            }
        }

        return Response(data)


class Forgot_Password_View(APIView):
    """
    发送邮箱
    """

    def post(self, request):
        username = request.data.get('username')
        email = request.data.get('email')
        print(username, email)
        if not all([username, email]):
            return Response({"msg": "参数不完整", "code": 400})

        user_obj = User.objects.filter(username=username).first()
        print(user_obj)
        if user_obj:

            send_mail_task.delay(username, email, user_obj.id)

            return Response({"msg": "邮箱发送成功", "code": 200})
        else:
            return Response({'msg': "err"})


class UpdatePwd(APIView):
    def put(self, request):
        uid = request.data.get('uid')
        password = request.data.get('password')
        print(uid, password)

        userobj = User.objects.filter(id=uid).update(
            password=make_password(password)
        )
        return Response({'code': 200, 'msg': '修改成功'})


class RoleView(APIView):
    def post(self, request):
        data = request.data
        obj = RoleSerializer(data=data)
        if obj.is_valid():
            obj.save()
            return Response({'code': 200, 'msg': '添加成功'})

        print(obj.errors)
        return Response({'code': 400, 'msg': '添加失败'})

    def get(self, request):
        role_obj = Role.objects.all()
        obj = RoleSerializer(role_obj, many=True)
        return Response(obj.data)


class UserAddRoleView(APIView):
    def post(self, request):
        uid = request.data.get('uid')
        rid = request.data.get('rid')
        print(uid, '*************')
        print(rid, '*************')
        if not all([uid, rid]):
            return Response({'msg': '参数不完整', 'code': 400})
        user_obj = User.objects.filter(id=uid).first()
        role_obj = Role.objects.filter(id__in=rid)
        user_obj.roles.add(*role_obj)
        return Response({'msg': '添加成功', 'code': 200})


class DeleteView(APIView):
    def delete(self, request):
        role_id = request.GET.get('id')

        Role.objects.get(id=role_id).delete()
        return Response({'code': 200, 'msg': '删除成功'})


class TestView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        return Response({'code': 200, 'msg': 'OK'})


class UserViewSet(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class RoleViewSet(ModelViewSet):
    queryset = Role.objects.all()
    serializer_class = RoleSerializer

